package com.open.pay.wechat.infrastructure.config;

import com.open.framework.exception.BusinessException;
import com.open.pay.wechat.infrastructure.common.constant.PayConstant;
import com.open.pay.wechat.infrastructure.config.wxpaysdk.IWXPayDomain;
import com.open.pay.wechat.infrastructure.config.wxpaysdk.WXPayConfig;
import com.open.pay.wechat.infrastructure.config.wxpaysdk.WXPayDomainSimpleImpl;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author zhang kaichao
 */
@Slf4j
@EqualsAndHashCode(callSuper = true)
@Data
public class WxPayConfigStorageImpl extends WXPayConfig {

    private String notifyUrl;
    private String appID;
    private String mchID;
    private String key;
    private String signType;
    private int httpConnectTimeoutMs;
    private int httpReadTimeoutMs;
    private Boolean useSandbox = Boolean.FALSE;
    private String certName = PayConstant.CERT_NAME;
    private byte[] certData;

    @Override
    public InputStream getCertStream() {
        return new ByteArrayInputStream(this.certData);
    }

    @Override
    public IWXPayDomain getWXPayDomain() {
        return WXPayDomainSimpleImpl.instance();
    }

    public void setCertData() {
        try {
            InputStream certStream = WxPayConfigStorageImpl.class.getClassLoader().getResourceAsStream(this.certName);
            assert certStream != null;
            this.certData = new byte[certStream.available()];
            certStream.read(certData);
            certStream.close();
        } catch (Exception e) {
            log.error("## /setCertData fail:", e);
            throw new BusinessException("加载证书异常");
        }
    }
}
